package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.*;
import com.xxxx.server.pojo.*;
import com.xxxx.server.pojo.result.EmployeeResult;
import com.xxxx.server.service.IEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.time.ZoneOffset;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-10-15
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PositionMapper positionMapper;
    @Autowired
    private NationMapper nationMapper;
    @Autowired
    private JoblevelMapper joblevelMapper;
    @Autowired
    private PoliticsStatusMapper politicsStatusMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private SimpleMailMessage message;

    /**
     * 查询员工
     * @param currentPage
     * @param size
     * @param employee
     * @return
     */
    @Override
    public EmployeeResult selectAllEmployee(Integer currentPage, Integer size,Employee employee,String beginDateScope) {
        EmployeeResult employeeResult = new EmployeeResult();
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        System.out.println(employee);
        if(!StringUtils.isBlank(employee.getName())){
            wrapper.like("name",employee.getName());
        }else{
            if(employee.getPoliticId()!=null&&employee.getPoliticId()!=0){
                wrapper.eq("politicId",employee.getPoliticId());
            }
            if(employee.getNationId()!=null&&employee.getNationId()!=0){
                wrapper.eq("nationId",employee.getNationId());
            }
            if(employee.getPosId()!=null&&employee.getPosId()!=0){
                wrapper.eq("posId",employee.getPosId());
            }
            if(employee.getJobLevelId()!=null&&employee.getJobLevelId()!=0){
                wrapper.eq("jobLevelId",employee.getJobLevelId());
            }
            if(!StringUtils.isBlank(employee.getEngageForm())){
                wrapper.eq("engageForm",employee.getEngageForm());
            }
            if(employee.getDepartmentId()!=null&&employee.getDepartmentId()!=0){
                wrapper.eq("departmentId",employee.getDepartmentId());
            }
            if(!StringUtils.isBlank(beginDateScope)){
                String beginDateLeft = beginDateScope.split(",")[0];
                String beginDateRight = beginDateScope.split(",")[1];
                wrapper.apply(StringUtils.isNotBlank(beginDateLeft),
                        "beginDate >= str_to_date('" + beginDateLeft + "','%Y-%m-%d')")
                        .apply(StringUtils.isNotBlank(beginDateRight),
                                "beginDate <= str_to_date('" + beginDateRight + "','%Y-%m-%d')");
            }
        }

        IPage<Employee> page = new Page<>(currentPage,size);
        employeeMapper.selectPage(page,wrapper);
        employeeResult.setData(page.getRecords());
        employeeResult.setTotal(page.getTotal());
        //System.out.println(page.getTotal());
        return employeeResult;
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    public RespBean add(Employee employee) {

        int index = employeeMapper.insert(employee);
        if(index>0){//发送邮件(异步 应该用消息队列写)
            // 设置邮件主题
            message.setSubject("这是一封入职邮件");
            // 设置邮件发送者，这个跟application.yml中设置的要一致
            message.setFrom("2773905608@qq.com");
            // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
            // message.setTo("10*****16@qq.com","12****32*qq.com");
            message.setTo(employee.getEmail());
            // 设置邮件抄送人，可以有多个抄送人
            //message.setCc("12****32*qq.com");
            // 设置隐秘抄送人，可以有多个
            //message.setBcc("7******9@qq.com");
            // 设置邮件发送日期
            message.setSentDate(new Date());
            // 设置邮件的正文
            message.setText("恭喜"+employee.getName()+"，您已经成为牛逼集团的员工");
            // 发送邮件
            javaMailSender.send(message);
            return RespBean.success("员工添加成功");
        }
        return RespBean.error("员工添加失败");
    }

    /**
     * 获取最大工号
     * @return
     */
    @Override
    public RespBean getMaxWorkID() {
        Integer index = employeeMapper.selectCount(null)+1;
        int temp= index;
        //System.out.println(index);
        int count=1;
        while(true) {
            if(index / 10 == 0) {
                break;
            } else {
                index = index / 10;
                count++;
            }
        }
        StringBuilder  workID=new StringBuilder();
        for(int i=0;i<8-count;i++){
            workID.append("0");
        }
        workID.append(temp);
        return RespBean.success("最大工号获取成功",workID);
    }

    @Override
    public List<Position> getPositions() {
        return positionMapper.selectList(null);
    }


    @Override
    public List<Nation> getNations() {
        return nationMapper.selectList(null);
    }

    @Override
    public List<Joblevel> getJoblevels() {
        return joblevelMapper.selectList(null);
    }

    @Override
    public List<PoliticsStatus> getPoliticsStatuss() {
        return politicsStatusMapper.selectList(null);
    }

    @Override
    public List<Department> getDepartments() {
        return departmentMapper.selectList(null);
    }

    @Override
    public RespBean delete(Integer id) {
        int i = employeeMapper.deleteById(id);
        if(i>0){
            return RespBean.success("员工删除成功");
        }
        return RespBean.error("员工删除失败");
    }

    @Override
    public RespBean edit(Employee emp) {
        int i = employeeMapper.updateById(emp);
        if(i>0){
            return RespBean.success("员工修改成功");
        }
        return RespBean.error("员工修改失败");
    }

    @Override
    public void exportData(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        List<Employee> classmateList = employeeMapper.selectList(null);

        String fileName = "employeeinf"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = {"姓名","工号", "性别","出生日期","身份证号码","婚姻状况","民族","籍贯","政治面貌","电子邮件","电话号码","联系地址","所属部门","职称","职位","聘用形式","最高学历","毕业院校","专业","在职状态","入职日期","转正日期","合同起始日期","合同截止日期","合同期限"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Employee employee : classmateList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(employee.getName());
            row1.createCell(1).setCellValue(employee.getWorkID());
            row1.createCell(2).setCellValue(employee.getGender());

            row1.createCell(3).setCellValue(employee.getBirthday().toString());
            row1.createCell(4).setCellValue(employee.getIdCard());
            row1.createCell(5).setCellValue(employee.getWedlock());
            row1.createCell(6).setCellValue(employee.getNationId());
            row1.createCell(7).setCellValue(employee.getNativePlace());
            row1.createCell(8).setCellValue(employee.getPoliticId());
            row1.createCell(9).setCellValue(employee.getEmail());
            row1.createCell(10).setCellValue(employee.getPhone());
            row1.createCell(11).setCellValue(employee.getAddress());
            row1.createCell(12).setCellValue(employee.getDepartmentId());
            row1.createCell(13).setCellValue(employee.getJobLevelId());
            row1.createCell(14).setCellValue(employee.getPosId());
            row1.createCell(15).setCellValue(employee.getEngageForm());
            row1.createCell(16).setCellValue(employee.getTiptopDegree());
            row1.createCell(17).setCellValue(employee.getSchool());
            row1.createCell(18).setCellValue(employee.getSpecialty());
            row1.createCell(19).setCellValue(employee.getWorkState());
            row1.createCell(20).setCellValue(employee.getBeginDate().toString());
            row1.createCell(21).setCellValue(employee.getConversionTime().toString());
            row1.createCell(22).setCellValue(employee.getBeginContract().toString());
            row1.createCell(23).setCellValue(employee.getEndContract().toString());
            row1.createCell(24).setCellValue(employee.getContractTerm());
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    public void adds(List<Employee> list){

    }
}
